var util = require("../../utils/uitl.js");
let app = getApp();
Page({
  //RESTful  一种数据接口设计规范
  data: {
    top250: {},
    comingSoon: {},
    inTheaters: {},
    searchResult: {},
    containerShow:true,
    searchPanelShow:false
  },
  onLoad: function() {
    var top250Url = app.globalData.doubanBase + "/v2/movie/top250" + "?start=0&count=3";
    var comingSoonUrl = app.globalData.doubanBase + "/v2/movie/coming_soon" + "?start=0&count=3";
    var inTheatersUrl = app.globalData.doubanBase + "/v2/movie/in_theaters" + "?start=0&count=3";
    //网络请求
    this.getMovieListData(inTheatersUrl, "inTheaters", "正在热映");
    this.getMovieListData(comingSoonUrl, "comingSoon", "即将上映");
    this.getMovieListData(top250Url, "top250","豆瓣Top250");
  },

  //点击跳转"更多"页面
  onMoreTap: function (event) {
    //定义当前点击的那个分类
    var category = event.currentTarget.dataset.category;
    wx.navigateTo({
      //路径下的分类就等于点击的那个分类
      url: "more-movie/more-movie?category=" + category
    })
  },

  //跳转电影详情页
  onMovieTap: function (event) {
    //电影的id序号
    var movieId = event.currentTarget.dataset.movieid
    wx.navigateTo({
      url: "movie-detail/movie-detail?id="+movieId
    })
  },

  //电影获取函数
  getMovieListData: function (url, setedKey, categoryTitle) {
    var that = this;
    wx.request({
      url: url,
      method: 'GET',
      data: {},
      header: {
        "Content-Type": "application/json"
      },
      success: function(res) {
        console.log(res)
        that.processDoubanData(res.data, setedKey, categoryTitle)
      },
      fail: function(res) {
        console.log(res)
      }
    })
  },
  
  onCancelImgTap:function(event){
    this.setData({
      containerShow:true,
      searchPanelShow:false,
    })
  },

  //获取焦点后改变状态
  onBindFocus:function (event) {
      console.log("触发 focus")
      this.setData({
        containerShow:false,
        searchPanelShow:true
      })
  },
  
  //获取搜索结果
  onBindchange:function (event) {
    //获取用户输入的值
    var text = event.detail.value;
    var searchUrl = app.globalData.doubanBase + "/v2/movie/search?q=" + text;
    this.getMovieListData(searchUrl,"searchResult","");
  },

  //处理豆瓣数据
  processDoubanData: function (moviesDouban, setedKey, categoryTitle) {
    var movies = [];
    for (var idx in moviesDouban.subjects) {
      var subject = moviesDouban.subjects[idx];
      var title = subject.title;
      if (title.length >= 6) {
        title = title.substring(0, 6) + "...";
      }
      var temp = {
        //星星组件
        //stars: util.convertToStarsArray(subject.rating.stars),
        //标题
        title: title,
        //评分
        average: subject.rating.average,
        //海报
        coverageUrl: subject.images.large,
        //电影序号
        movieId: subject.id
      }
      //把temp推到movies数组里
      movies.push(temp);
    }
    var readyData = {};
    readyData[setedKey] = {
      categoryTitle: categoryTitle,
      movies:movies
    }
    this.setData(readyData);
  }
})